package cn.iocoder.yudao.module.system.controller.admin.a_article;

import cn.hutool.http.HtmlUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.module.system.controller.admin.a_article.vo.*;
import cn.iocoder.yudao.module.system.dal.dataobject.a_article.ArticleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.a_article.ArticleDOReq;
import cn.iocoder.yudao.module.system.dal.dataobject.a_article.ArticleTempDO;
import cn.iocoder.yudao.module.system.service.a_article.ArticleService;
import cn.iocoder.yudao.module.system.config.a_gaojian.CkmConfig;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.core.io.ResourceLoader;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 稿件管理 - 文稿")
@RestController
@RequestMapping("/system/article")
@Validated
public class ArticleController {

    @Resource
    ResourceLoader resourceLoader;

    @Resource
    ArticleService articleService;

    @PostMapping("/create")
    @Operation(summary = "新增文稿")
    @PreAuthorize("@ss.hasPermission('system:article:create')")
    public CommonResult<String> create(@Valid @RequestBody ArticleReqVO articleReqVO) {
        return success(articleService.insertHybaseByArticle(articleReqVO));
    }

    @PostMapping("/uploadInset")
    @Operation(summary = "新增插图")
    public Map<String, String> uploadInset(@RequestParam("action") String action, @RequestParam(value = "upfile", required = false) MultipartFile upfile) {
        //图片上传
        Map<String, String> map = new HashMap<>();
        map.put("state", "SUCCESS");
        map.put("url", articleService.uploadInset(upfile));
        map.put("title", upfile.getOriginalFilename());
        map.put("original", upfile.getOriginalFilename());
        return map;
    }


    @GetMapping("/uploadInset")
    @Operation(summary = "获取ueditor配置文件")
    @PermitAll
    public JSONObject config() {
        org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:config.json");
        byte[] bytes = new byte[0];
        try {
            InputStream inputStream = resource.getInputStream();
            bytes = new byte[inputStream.available()];
            inputStream.read(bytes);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return JSONObject.parseObject(bytes, JSONObject.class);
    }

    @DeleteMapping("/deleteInset")
    @Operation(summary = "删除插图")
    @PreAuthorize("@ss.hasPermission('system:article:delete')")
    public CommonResult<Boolean> deleteInset(@RequestParam("insetUrls") String insetUrls) {
        return success(articleService.deleteInset(insetUrls));
    }

    @GetMapping("/page")
    @Operation(summary = "获得文稿分页")
    @PreAuthorize("@ss.hasPermission('system:article:query')")
    public CommonResult<PageResult<ArticlePageReqVO>> getPage(@Valid ArticlePageReqVO pageVO) {
        PageResult<ArticlePageReqVO> pageResult = articleService.getPage(pageVO);
        return success(pageResult);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除文稿")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('system:article:delete')")
    public CommonResult<String> delete(@Valid ArticleDeleteReqVO deleteReqVO) {
        if (articleService.delete(deleteReqVO.getIds(), deleteReqVO.getCoverUrls())) {
            return success("删除成功");
        } else {
            return success("删除失败");
        }
    }

    @GetMapping("/get")
    @Operation(summary = "获得文稿")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:article:query')")
    public CommonResult<ArticleDO> get(@RequestParam("id") String id) {
        return success(articleService.get(id));
    }

    @PutMapping("/update")
    @Operation(summary = "更新文稿")
    @PreAuthorize("@ss.hasPermission('system:article:update')")
    public CommonResult<String> update(@Valid @RequestBody ArticleReqVO updateReqVO) {
        if (StringUtils.isNotBlank(updateReqVO.getId())) {
            if (articleService.updateHybaseByArticle(updateReqVO)) {
                return success("修改成功");
            } else {
                return success("修改失败");
            }
        }
        return success("修改失败，参数缺失！");
    }


    @PostMapping("/duplicate")
    @Operation(summary = "文稿内容查重")
    @PreAuthorize("@ss.hasPermission('system:article:query')")
    public CommonResult<Map<String, Object>> duplicate(@Valid @RequestBody ArticleDuplicateReqVO articleDuplicateReqVO) {
        return success(articleService.duplicate(articleDuplicateReqVO));
    }


    @PutMapping("/insertArticleTemp")
    @Operation(summary = "文稿暂存")
    @PreAuthorize("@ss.hasPermission('system:article:create')")
    public CommonResult<Boolean> insertArticleTemp(@Valid ArticleReqVO articleReqVO) {
        return success(articleService.insertArticleTemp(articleReqVO));
    }

    @DeleteMapping("/deleteArticleTemp")
    @Operation(summary = "删除全部暂存文稿")
    @PreAuthorize("@ss.hasPermission('system:article:delete')")
    public CommonResult<Boolean> deleteArticleTemp(@org.springframework.web.bind.annotation.RequestBody Long[] ids) {
        return success(articleService.deleteArticleTemp(ids));
    }


    @GetMapping("/getArticleTemp")
    @Operation(summary = "获得最新暂存文稿")
    @PreAuthorize("@ss.hasPermission('system:article:query')")
    public CommonResult<ArticleTempDO> getArticleTemp(@RequestParam("relevanceId") String relevanceId) {
        return success(articleService.getArticleTemp(relevanceId));
    }

    @PostMapping("/updateReview")
    @Operation(summary = "提交审核")
    @PreAuthorize("@ss.hasPermission('system:article:update')")
    public CommonResult<Boolean> updateReview(@RequestParam("id") String id) {
        return success(articleService.updateReview(id, 1));
    }

    @PostMapping("/updateShare")
    @Operation(summary = "共享素材")
    @PreAuthorize("@ss.hasPermission('system:article:update')")
    public CommonResult<Boolean> updateShare(@RequestParam("id") String id, @RequestParam("shareStatus") String shareStatus) {
        return success(articleService.updateShare(id, shareStatus));
    }

    @PostMapping("/updatePush")
    @Operation(summary = "推送资源库")
    @PreAuthorize("@ss.hasPermission('system:article:update')")
    public CommonResult<Boolean> updatePush(@RequestParam("id") String id, @RequestParam("pushStatus") String pushStatus) {
        return success(articleService.updatePush(id, pushStatus));
    }

    @PostMapping("/getRLPicturesPage")
    @Operation(summary = "资源库图片")
    public CommonResult<PageResult<AticleRLPicturesPageReqVO>> getRLPicturesPage(@Valid @RequestBody AticleRLPicturesPageReqVO pageReqVO) {
        PageResult<AticleRLPicturesPageReqVO> pageResult = articleService.getRLPicturesPage(pageReqVO);
        return success(pageResult);
    }

    @PostMapping("/getRLVideoPage")
    @Operation(summary = "资源库视频")
    public CommonResult<PageResult<AticleRLVideoPageReqVO>> getRLVideoPage(@Valid @RequestBody AticleRLVideoPageReqVO pageReqVO) {
        PageResult<AticleRLVideoPageReqVO> pageResult = articleService.getRLVideoPage(pageReqVO);
        return success(pageResult);
    }

    @PostMapping("/creatModel")
    @Operation(summary = "创建文稿查重模板")
    public CommonResult<Boolean> creatModel() {
        return success(articleService.creatModel());
    }


    @PostMapping("/getAbs")
    @Operation(summary = "智能生成标题")
    @OperateLog(enable = false)
    public CommonResult<String> getAbs(@org.springframework.web.bind.annotation.RequestBody String content) {
        CkmConfig ckmConfig = new CkmConfig();
        return success(ckmConfig.getAbs(HtmlUtil.cleanHtmlTag(content)));
    }

    @PutMapping("save")
    @Operation(summary = "文稿保存")
    @PreAuthorize("@ss.hasPermission('system:article:update')")
    public CommonResult<Long> save(@Validated ArticleDOReq articleDO) {
        return CommonResult.success(articleService.save(articleDO));
    }

    @DeleteMapping("/deleteById")
    @Operation(summary = "根据id删除")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('system:article:delete')")
    public CommonResult<Boolean> deleteById(@org.springframework.web.bind.annotation.RequestBody Long[] ids) {
        return CommonResult.success(articleService.delete(ids));
    }

    @GetMapping("/select/page")
    @Operation(summary = "获得分页")
    @PreAuthorize("@ss.hasPermission('system:article:query')")
    public CommonResult<PageResult<ArticleDO>> selectPage(@Valid ArticlePageReqVO pageVO) {
        return success(articleService.selectPage(pageVO));
    }

}
